<template>
  <view class="temple-list">
    <!-- 顶部操作栏 -->
    <view v-if="!querys?.familyId" class="header-actions">
      <!-- 筛选 -->
      <wd-drop-menu close-on-click-modal class="filter-menu">
        <wd-drop-menu-item ref="filterDropMenu" title="筛选" icon="filter" icon-size="16px">
          <view>
            <wd-input
              v-model="queryParams.keywords"
              label="关键字"
              type="text"
              placeholder="请输入宗祠名称"
            />
            <view class="filter-actions">
              <wd-button class="reset-btn" type="info" size="small" @click="handleResetQuery">
                重置
              </wd-button>
              <wd-button class="query-btn" size="small" @click="handleQuery">查询</wd-button>
            </view>
          </view>
        </wd-drop-menu-item>
      </wd-drop-menu>
    </view>
    <!-- 我的宗祠模式 - 当mySelf=true时 -->
    <view v-if="querys?.mySelf === 'true'">
      <!-- 有数据时显示宗祠信息 -->
      <view v-if="templeList && templeList.length > 0">
        <wd-card
          v-for="item in templeList"
          :key="item.id"
          class="temple-card"
          @click="goToDetail(item.id)"
        >
          <template #title>
            <view class="card-title">
              <text>{{ item.templeName }}</text>
              <text class="card-subtitle">{{ item.subTitle }}</text>
            </view>
          </template>

          <view class="card-content">
            <view class="image-container">
              <view class="image-loading" v-if="!item.imageLoaded">
                <wd-loading size="small" type="ring" />
              </view>
              <image
                class="temple-image"
                :src="item.coverImage || 'https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/53a8e9ec024d4446886c1c0f0efee8c7.png'"
                mode="aspectFill"
                lazy-load
                @load="item.imageLoaded = true"
              />
            </view>
            <view class="temple-info">
              <view class="info-item">
                <text class="info-label">地址：</text>
                <text class="info-value">{{ item.location }}</text>
              </view>
              <view class="info-item">
                <text class="info-label">负责人：</text>
                <text class="info-value">{{ item.manager }}</text>
              </view>
              <view class="info-item">
                <text class="info-label">开放时间：</text>
                <text class="info-value">
                  {{ item.openingHours ? item.openingHours : "暂未开放" }}
                </text>
              </view>
            </view>
          </view>

          <template #footer>
            <view class="card-footer">
              <view class="create-time">
                <text class="time-label">创建时间：</text>
                <text class="time-value">{{ item.createTime }}</text>
              </view>
              <wd-button type="primary" size="small" @click.stop="goToDetail(item.id)">
                查看详情
              </wd-button>
            </view>
          </template>
        </wd-card>
      </view>

      <!-- 无数据时显示空状态和创建按钮 -->
      <view v-else-if="!loading && querys?.mySelf === 'true'" class="no-temple">
        <view class="no-temple-desc">您的家族暂无祠堂记录</view>
        <view class="no-temple-button" @click="goToAdd">创建宗祠</view>
      </view>
    </view>

    <!-- 非mySelf模式下的宗祠列表 -->
    <view v-if="querys?.mySelf !== 'true'">
      <!-- 全部宗祠列表 -->
      <view v-if="templeList.length" class="all-temple">
        <view class="section-header-list">
          <view class="section-title">{{ querys?.familyId ? "我的家族祠堂" : "全部宗祠" }}</view>
          <view class="temple-count">共 {{ total }} 个</view>
        </view>
        <view class="temple-list-content">
          <wd-card
            v-for="item in templeList"
            :key="item.id"
            class="temple-card"
            @click="goToDetail(item.id)">
            <template #title>
              <view class="card-title">
                <text>{{ item.templeName }}</text>
                <text class="card-subtitle">{{ item.subTitle }}</text>
              </view>
            </template>

            <view class="card-content">
              <view class="image-container">
                <view class="image-loading" v-if="!item.imageLoaded">
                  <wd-loading size="small" type="ring" />
                </view>
                <image
                  class="temple-image"
                  :src="item.coverImage || 'https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/53a8e9ec024d4446886c1c0f0efee8c7.png'"
                  mode="aspectFill"
                  lazy-load
                  @load="item.imageLoaded = true"
                />
              </view>
              <view class="temple-info">
                <view class="info-item">
                  <text class="info-label">地址：</text>
                  <text class="info-value">{{ item.location }}</text>
                </view>
                <view class="info-item">
                  <text class="info-label">负责人：</text>
                  <text class="info-value">{{ item.manager }}</text>
                </view>
                <view class="info-item">
                  <text class="info-label">开放时间：</text>
                  <text class="info-value">
                    {{ item.openingHours ? item.openingHours : "暂未开放" }}
                  </text>
                </view>
              </view>
            </view>

            <template #footer>
              <view class="card-footer">
                <view class="create-time">
                  <text class="time-label">创建时间：</text>
                  <text class="time-value">{{ item.createTime }}</text>
                </view>
                <wd-button type="primary" size="small" @click.stop="goToDetail(item.id)">
                  查看详情
                </wd-button>
              </view>
            </template>
          </wd-card>
        </view>
      </view>

      <!-- 加载更多 -->
      <wd-loadmore
        v-if="total > 0 && templeList.length > 0"
        :state="loadMoreState"
        @reload="loadmore"
      />

      <!-- 空状态 - 非mySelf模式 -->
      <view
        v-if="querys?.mySelf !== 'true' && templeList.length === 0 && !loading"
        class="empty-state"
      >
        <view class="empty-content">
          <view class="empty-text">
            <text class="empty-title">暂无宗祠信息</text>
            <text class="empty-desc">
              {{
                querys?.familyId ? "您的家族暂无祠堂记录" : "暂无宗祠数据，您可以尝试其他筛选条件"
              }}
            </text>
          </view>
          <!-- 只有mySelf=true时显示创建按钮 -->
          <wd-button
            v-if="querys?.mySelf === 'true' && querys?.familyId"
            type="primary"
            size="large"
            icon="add"
            class="empty-button"
            @click="goToAdd"
          >
            创建宗祠
          </wd-button>
        </view>
      </view>

      <!-- 加载状态 -->
      <view v-if="loading" class="loading-container">
        <wd-loading size="large" />
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, onUnmounted } from "vue";
import { onReachBottom } from "@dcloudio/uni-app";
import { LoadMoreState } from "wot-design-uni/components/wd-loadmore/types";
import { DropMenuItemExpose } from "wot-design-uni/components/wd-drop-menu-item/types";
interface TempleItem {
  id: number | string;
  templeName: string;
  subTitle?: string;
  coverImage?: string;
  location: string;
  manager: string;
  openingHours?: string;
  createTime: string;
  description?: string;
  history?: string;
  familyId?: number | string;
  imageLoaded?: boolean;
}

interface TempleListResponse {
  list: TempleItem[];
  total: number;
}

import { getTempleList } from "../../../api/temple";
// const selectedFamily = JSON.parse(uni.getStorageSync('selectedFamily'))

// 筛选组件引用
const filterDropMenu = ref<DropMenuItemExpose>();
const loadMoreState = ref<LoadMoreState>("loading");

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  keywords: undefined as string | undefined,
});

// 数据列表
const templeList = ref<TempleItem[]>([]);
const total = ref(0);
const loading = ref(false);
const querys = ref<{
  familyId: string;
}>();

// 路由类型和权限控制 - 参考clanList.vue和ModuleList.vue
const routeType = ref("all"); // 'once' 我的宗祠, 'all' 全部宗祠
const myTempleData = ref<TempleItem | null>(null); // 我的宗祠数据

// 计算属性：判断是否应该显示创建宗祠按钮
const canCreateTemple = computed(() => {
  // 只有mySelf=true模式才显示创建按钮
  return querys.value?.mySelf === "true";
});

// 权限检查函数 - 参考ModuleList.vue
const hasPermission = () => {
  try {
    const userInfo = uni.getStorageSync("user-info");
    if (userInfo && userInfo.areaCodeScope) {
      // 族长或管理员权限
      return userInfo.areaCodeScope === 6 || userInfo.areaCodeScope === 2;
    }
    return false;
  } catch (error) {
    console.error("获取用户权限失败", error);
    return false;
  }
};

/**
 * 查询 - 根据路由参数选择数据获取方式
 * 1. mySelf=true：通过familyId获取对应宗祠（显示创建按钮）
 * 2. type=once且无mySelf：通过familyId获取对应宗祠（不显示创建按钮）
 * 3. 无参数：获取全部宗祠列表（不显示创建按钮）
 */
function handleQuery() {
  filterDropMenu.value?.close();
  queryParams.pageNum = 1;

  if (querys.value?.mySelf === "true") {
    // 模式1：mySelf=true，通过familyId获取宗祠信息，无数据时显示创建按钮
    getMyTemple();
  } else if (routeType.value === "once" && querys.value?.familyId) {
    // 模式2：type=once且无mySelf，通过familyId获取宗祠信息，无数据时不显示创建按钮
    getMyTemple();
  } else {
    // 模式3：无参数或type=all，获取全部宗祠列表
    getAllTempleList();
  }
}

/**
 * 重置查询 - 更新以支持不同模式
 */
function handleResetQuery() {
  queryParams.keywords = undefined;
  handleQuery();
}

/**
 * 处理宗祠点击 - 参考clanList.vue的handleClan
 */
function handleTemple(temple: TempleItem) {
  const flag = querys.value.familyId === temple.familyId?.toString();
  uni.navigateTo({
    url: `/pages/work/family/detail?id=${temple.id}&familyId=${temple.familyId || ""}`,
  });
}

/**
 * 获取全部宗祠列表 - 无参数模式或列表模式
 */
const getAllTempleList = () => {
  loading.value = true;
  loadMoreState.value = "loading";

  // 清空现有数据
  if (queryParams.pageNum === 1) {
    templeList.value = [];
  }

  getTempleList({
    pageNum: queryParams.pageNum.toString(),
    pageSize: queryParams.pageSize.toString(),
    familyId: querys.value.familyId || undefined,
    keywords: queryParams.keywords,
  })
    .then((res: TempleListResponse) => {
      const formattedList = (res.list || []).map(item => ({
        ...item,
        imageLoaded: false
      }));
      
      if (queryParams.pageNum === 1) {
        templeList.value = formattedList;
      } else {
        templeList.value = [...templeList.value, ...formattedList];
      }
      total.value = res.total || 0;

      loadMoreState.value =
        queryParams.pageNum * queryParams.pageSize >= total.value
          ? "finished"
          : ("loadmore" as LoadMoreState);
    })
    .catch((error: any) => {
      uni.showToast({
        title: "网络异常，请稍后重试",
        icon: "none",
      });
      console.error("获取宗祠列表失败:", error);
      loadMoreState.value = "error";
      templeList.value = [];
    })
    .finally(() => {
      loading.value = false;
    });
};

/**
 * 获取我的宗祠 - 根据familyId获取单条宗祠信息
 */
const getMyTemple = () => {
  loading.value = true;

  getTempleList({
    pageNum: "1",
    pageSize: "10",
    familyId: querys.value?.familyId || undefined,
  })
    .then((res: TempleListResponse) => {
      if (res && res.list && res.list.length > 0) {
        // 根据familyId筛选出对应的宗祠
        // 只取第一条数据并添加imageLoaded字段
        templeList.value = res.list.map(item => ({
          ...item,
          imageLoaded: false
        }));
      } else {
        templeList.value = [];
      }
    })
    .catch((error: any) => {
      console.error("获取宗祠信息失败:", error);
      templeList.value = [];
      uni.showToast({
        title: "获取宗祠信息失败",
        icon: "none",
      });
    })
    .finally(() => {
      loading.value = false;
    });
};

/**
 * 加载更多数据 - 触底加载
 */
function loadmore() {
  if (loading.value || loadMoreState.value === "finished") {
    return;
  }

  // mySelf模式和once模式都是单条数据，不需要加载更多
  if (querys.value?.mySelf === "true" || (routeType.value === "once" && querys.value?.familyId)) {
    loadMoreState.value = "finished";
    return;
  }

  queryParams.pageNum += 1;
  getAllTempleList();
}

/**
 * 跳转到详情页
 */
function goToDetail(id: number | string) {
  uni.navigateTo({
    url: `/pages/work/family/detail?id=${id}`,
  });
}

/**
 * 跳转到新增宗祠页面
 */
function goToAdd() {
  uni.navigateTo({
    url: "/pages/work/family/AddTemplePopup",
  });
}

/**
 * 触底加载更多
 */
onReachBottom(() => {
  if (queryParams.pageNum * queryParams.pageSize < total.value) {
    loadmore();
  } else {
    loadMoreState.value = "finished";
  }
});

// 页面加载时获取数据
onMounted(() => {
  // 监听新增宗祠成功后的刷新事件
  uni.$on("refreshTempleList", () => {
    handleQuery();
  });
});

// 页面卸载时移除监听
onUnmounted(() => {
  uni.$off("refreshTempleList");
});

/**
 * 下拉刷新 - 重置数据
 */
function onRefresh() {
  queryParams.pageNum = 1;

  if (querys.value?.mySelf === "true") {
    getMyTemple();
  } else if (routeType.value === "once" && querys.value?.familyId) {
    getMyTemple();
  } else {
    getAllTempleList();
  }
}


// 分享给朋友
const onShareAppMessage = () => {
  return {
    title: "数字家谱系统 - 连接家族，传承文化",
    path: "/pages/work/family/list",
    // imageUrl: "/static/images/default_banner.png",
  };
};

// 分享到朋友圈
const onShareTimeline = () => {
  return {
    title: "数字家谱系统 - 连接家族，传承文化",
    query: "share=true",
    // imageUrl: "/static/images/default_banner.png",
  };
};

// 导出生命周期钩子
defineExpose({
  onShareAppMessage,
  onShareTimeline,
});

onLoad((query) => {
  querys.value = query as {
    familyId: string;
    mySelf?: string;
    type?: string;
  };

  // 路由类型判断
  if (querys.value.mySelf === "true") {
    routeType.value = "my"; // 模式1：mySelf=true
  } else if (query.type === "once" && querys.value.familyId) {
    routeType.value = "once"; // 模式2：type=once且有familyId
  } else {
    routeType.value = query.type || (querys.value.familyId ? "once" : "all"); // 模式3：其他情况
  }

  console.log("路由参数:", querys.value);
  console.log("路由类型:", routeType.value);

  // 设置页面标题
  if (querys.value.mySelf === "true") {
    uni.setNavigationBarTitle({
      title: "我的宗祠",
    });
  } else if (routeType.value === "once") {
    uni.setNavigationBarTitle({
      title: "家族祠堂",
    });
  } else {
    uni.setNavigationBarTitle({
      title: "宗祠列表",
    });
  }

  // 初始加载数据
  handleQuery();
});



</script>

<style lang="scss">
page {
  background: #f5f5f5;
  font-size: 28rpx;
}

.temple-list {
  padding: 0 0 20rpx 0;
}

.header-actions {
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 16rpx;
  .filter-menu {
    flex: 1;
    width: 100%;
    margin-bottom: 0;
    border-radius: 0;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  }

  wd-button {
    flex-shrink: 0;
  }
}

.full-width {
  margin-left: -16rpx;
  margin-right: -16rpx;
  width: calc(100% + 32rpx);
}

.filter-actions {
  display: flex;
  padding: 16rpx 0;

  .reset-btn {
    flex: 1;
    margin-right: 16rpx;
  }

  .query-btn {
    flex: 3;
  }
}
.card-title {
  padding: 6rpx 0;

  text {
    font-size: 30rpx;
    font-weight: bold;
    color: #333;
  }

  .card-subtitle {
    display: block;
    font-size: 22rpx;
    color: #666;
    margin-top: 4rpx;
    font-weight: normal;
  }
}

.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 10rpx;
  border-top: 1rpx solid #eee;

  .create-time {
    font-size: 22rpx;

    .time-label {
      color: #666;
    }

    .time-value {
      color: #999;
    }
  }
}
  .card-content {
    display: flex;
    margin: 16rpx 0;

    .image-container {
      position: relative;
      width: 180rpx;
      height: 180rpx;
      border-radius: 8rpx;
      margin-right: 16rpx;
      flex-shrink: 0;
      background-color: #f5f5f5;
    }

    .image-loading {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      z-index: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      width: 100%;
      height: 100%;
    }

    .temple-image {
      width: 100%;
      height: 100%;
      border-radius: 8rpx;
      position: absolute;
      top: 0;
      left: 0;
    }

    .temple-info {
      flex: 1;
      overflow: hidden;

      .info-item {
        display: flex;
        margin-bottom: 10rpx;
        line-height: 1.5;

        .info-label {
          color: #666;
          flex-shrink: 0;
          width: 150rpx;
        }

        .info-value {
          color: #333;
          flex: 1;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
    }
  }
/* 空状态样式 */
.empty-state {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 60vh;
  padding: 40rpx 20rpx;
}

.empty-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

.empty-image {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 32rpx;
  opacity: 0.6;
}

.empty-text {
  margin-bottom: 48rpx;
}

.empty-title {
  display: block;
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 16rpx;
}

.empty-desc {
  display: block;
  font-size: 26rpx;
  color: #999;
  line-height: 1.5;
  max-width: 500rpx;
}

.empty-button {
  width: 240rpx;
  border-radius: 50rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.section-header-list {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 20rpx 20rpx 10rpx;
}

.temple-count {
  font-size: 26rpx;
  color: #999;
}

.no-temple {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 200rpx 40rpx 100rpx;
  background-color: #fff;
  border-radius: 20rpx;
  margin: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
}

.no-temple-desc {
  font-size: 28rpx;
  color: #999;
  margin-bottom: 40rpx;
  text-align: center;
}

.no-temple-button {
  padding: 20rpx 60rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
  font-size: 30rpx;
  border-radius: 50rpx;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4rpx 16rpx rgba(102, 126, 234, 0.3);
}

.no-temple-button:active {
  transform: scale(0.96);
  box-shadow: 0 2rpx 8rpx rgba(102, 126, 234, 0.2);
}
</style>
